<?php

if (!function_exists('num_format')) {
    /**
     * 数字格式化，千分位间隔，去除小数点末尾多余的零
     *
     * @param float $num
     * @param int|null $precision
     * @return string
     */
    function num_format(float $num, int $precision = null): string
    {
        if (is_null($precision)) {
            $precision = config('system.numeral.precision');
        }

        if ($precision <= 0) {
            return $num;
        }

        return rtrim(rtrim(number_format($num, $precision), '0'), '.');
    }
}

if (!function_exists('decimal_to_binary_bits')) {
    /**
     * 十进制转二进制位数组
     *
     * @param int|null $num
     * @return array
     */
    function decimal_to_binary_bits(?int $num): array
    {
        $bits = [];

        if (is_null($num) || $num <= 0) {
            return $bits;
        }

        for ($bit = 1; $bit <= $num; $bit *= 2) {
            if ($num & $bit) {
                array_push($bits, $bit);
            }
        }
        return $bits;
    }
}

if (!function_exists('timestamp_to_datetime')) {
    /**
     * 时间戳格式化为可读时间
     *
     * @param int $timestamp
     * @param string|null $type
     * @return false|string
     */
    function timestamp_to_datetime(int $timestamp, ?string $type = null, ?string $timezone = '')
    {
	    empty($timezone) && $timezone = \Helper\Timed::getTimezoneName();
		date_default_timezone_set($timezone);
        switch ($type) {
            case 'year':
                return date('YP', $timestamp);
            case 'month':
                return date('Y-mP', $timestamp);
            case 'day':
                return date('Y-m-dP', $timestamp);
            case 'hour':
                return date('Y-m-d H:00P', $timestamp);
            case 'minute':
                return date('Y-m-d H:iP', $timestamp);
            case 'second':
                return date('Y-m-d H:i:sP', $timestamp);
            case 'week':
                return date(trans('view.helpers.datetime.format_week'), $timestamp);
            case 'week.day':
                return date('Y-m-dP', $timestamp) . ' ~ ' . date('Y-m-dP', $timestamp + 86400 * 6);
            default:
                return date('c', $timestamp);
        }
    }
}
